<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\ProjectUser
 *
 * @property int $id
 * @property int|null $project_id
 * @property int|null $user_id
 * @property int|null $create_time
 * @property int|null $update_time
 * @property int|null $num
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser whereCreateTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser whereNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser whereProjectId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser whereUpdateTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\ProjectUser whereUserId($value)
 * @mixin \Eloquent
 * @property-read \App\User $user
 */
class ProjectUser extends Model
{
    protected $table = '5kcrm_project_user';
    public $timestamps = null;

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function current($project_id): int
    {
   /*     if ($project_id!=21&&$project_id!=26&&$project_id!=24&&$project_id!=27&&$project_id!=25&&$project_id!=16&&$project_id!=23&&$project_id!=29&&$project_id!=32&&$project_id!=20) {//中天联科 艾瑞克斯B组
            $userIds = ProjectUser::where('project_id', $project_id)->pluck('user_id')->toArray();
            return Customer::fenpei($userIds);*/

            $projectUser = ProjectUser::where('project_id', $project_id)->whereHas('user', function ($query) {
                $query->where('status', 1);
            })->where('num', 0)->first();

            if (!$projectUser) {
                ProjectUser::where('project_id', $project_id)->update(['num' => 0]);
            }
            $projectUser = ProjectUser::where('project_id', $project_id)->whereHas('user', function ($query) {
                $query->where('status', 1);
            })
                ->orderBy('num', 'asc')
                ->orderBy('id', 'asc')
                ->first();
            if ($projectUser) {
                $projectUser->num = 1 - $projectUser->num;
                $projectUser->save();
                return $projectUser->user_id;
            }
            return 1;
        }

}
